package com.jt.web.service.impl;

import com.jt.web.mapper.UserMapper;
import com.jt.web.pojo.User;
import com.jt.web.service.UserService;
import com.jt.web.utils.EStatus;
import com.jt.web.utils.ResultUtil;
import com.jt.web.utils.SysConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String Login(User user) {
        String password = DigestUtils.md5DigestAsHex(user.getPassWord().getBytes());
        user.setPassWord(password);
        User user1 = userMapper.login(user);
        if (user1 == null) {
            return ResultUtil.errorWithData("账号或密码错误！");
        }
        if (user1.getStatus() == EStatus.DISABLED) {
            return ResultUtil.errorWithData("该账号已被冻结！");
        }
        if (EStatus.FREEZE == user1.getStatus()) {
            return ResultUtil.result(SysConf.ERROR, "用户账号未激活");
        }
        user.setLastLoginTime(new Date());
        String token = user1.getPassWord() + " " + user1.getUserName();
        // 将token存入redis
        String redisKey = "token:" + user.getUid();
        stringRedisTemplate.opsForValue().set(redisKey, token, 1, TimeUnit.DAYS);
        return ResultUtil.successWithData(token);
    }
    /**
     * 通过userUid获取user信息
     * */
    @Override
    public User getUserByUid(String userUid) {
        Integer status = 1;
        User user = userMapper.getUserByUid(userUid,status);
        return user;

    }
    /**
     * 注册
     * */
    @Override
    public String register(User user) {
        if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassWord()))
            throw new RuntimeException("用户名或密码格式输入错误！");
        user.setPassWord(DigestUtils.md5DigestAsHex(user.getPassWord().getBytes()));
        user.setCommentStatus(1).setUserTag(0);
        user.setCreateTime(new Date()).setUpdateTime(new Date());
        int in = userMapper.insert(user);
        if(in != 1 ){
            return ResultUtil.errorWithData("注册失败！");
        }
        return ResultUtil.successWithData("注册成功！");
    }
}
